# pythonProject5/core/middleware.py

import time
import logging
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

logger = logging.getLogger(__name__)


async def log_request(request: Request, call_next):
	"""日志中间件：记录请求信息"""
	start_time = time.time()
	response = await call_next(request)
	process_time = time.time() - start_time
	log_dict = {
		"method": request.method,
		"url": str(request.url),
		"client_ip": request.client.host,
		"status_code": response.status_code,
		"process_time": f"{process_time:.3f}s",
	}

	# 记录用户信息（如果存在）
	user_id = None
	if hasattr(request.state, 'user') and request.state.user:
		user_id = request.state.user.get("id")
	if user_id:
		log_dict["user_id"] = user_id

	logger.info(f"HTTP {log_dict}")
	return response


async def add_process_time_header(request: Request, call_next):
	"""性能监控中间件：添加响应头 X-Process-Time"""
	start_time = time.time()
	response = await call_next(request)
	process_time = time.time() - start_time
	response.headers["X-Process-Time"] = f"{process_time:.3f}"
	return response


class LoggingMiddleware(BaseHTTPMiddleware):
	"""更精细的日志中间件（可选）"""

	async def dispatch(self, request: Request, call_next):
		start_time = time.time()
		response = await call_next(request)
		duration = time.time() - start_time
		logger.info(f"{request.method} {request.url.path} → {response.status_code} in {duration:.2f}s")
		return response
